﻿using EdgeSearch.Application.Manager.LogManager;
using Furion.Logging;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;

namespace EdgeSearch.Web.Core.Startups
{
    public static class LogStartup
    {
        public static IServiceCollection AddLogStartUp(this IServiceCollection services)
        {
            #region 日志配置
            //services.AddFileLogging("./logs/{0:yyyy}{0:MM}{0:dd}-info.log", options =>
            //{
            //    //每天写一个日志文件
            //    options.FileNameRule = fileName =>
            //    {
            //        return string.Format(fileName, DateTime.UtcNow);
            //    };
            //    options.WriteFilter = (logMsg) =>
            //    {
            //        return logMsg.LogLevel == LogLevel.Information;
            //    };
            //    options.FileSizeLimitBytes = 1024*1024*100;
            //    options.MaxRollingFiles = 7;
            //});
            //services.AddFileLogging("./logs/{0:yyyy}{0:MM}{0:dd}-error.log", options =>
            //{
            //    //Error Warning Trace 三个级别的日志都写入error.log
            //    options.WriteFilter = (logMsg) =>
            //    {
            //        List<LogLevel> levels = new List<LogLevel>() { LogLevel.Error, LogLevel.Warning, LogLevel.Trace };
            //        return levels.Contains(logMsg.LogLevel);
            //    };
            //    options.FileNameRule = fileName =>
            //    {
            //        return string.Format(fileName, DateTime.UtcNow);
            //    };
            //    options.FileSizeLimitBytes = 1024 * 1024 * 100;
            //    options.MaxRollingFiles = 7;
            //});
            ////启用监控日志
            services.AddMonitorLogging(options =>
            {
                //options.JsonBehavior = Furion.Logging.JsonBehavior.OnlyJson;
                options.ConfigureLogger((logger, logContext, context) =>
                {
                    var httpContext = context.HttpContext;
                    logContext.Set("Action", context.RouteData.Values["action"]);
                    logContext.Set("PageUrl", httpContext.Request.GetRequestUrlAddress());
                });
            });

            #endregion

            #region 日志写DB配置
            services.AddDatabaseLogging<DatabaseLoggingWriter>(options =>
            {
                var databaseLoggerSettings = App.GetConfig<DatabaseLoggerSettings>("Logging:DataBase");
                var MinimumLevel = databaseLoggerSettings?.MinimumLevel ?? LogLevel.Information;
                //options.MinimumLevel = MinimumLevel;
                options.WriteFilter = (logMsg) =>
                {
                    return logMsg.LogLevel >= MinimumLevel || logMsg.LogName == "System.Logging.LoggingMonitor";
                };

            });
            #endregion
            return services;
        }
    }
}
